//
//  YXOauthViewController.swift
//  微博YX
//
//  Created by apple on 15/11/24.
//  Copyright © 2015年 lyx. All rights reserved.
//

import UIKit

import SVProgressHUD


/// MARK: - 授权控制器
class YXOauthViewController: UIViewController {
    /// 懒加载
    lazy var webview = UIWebView()
    
    override func loadView() {
        self.view = webview
        webview.delegate = self
        webview.backgroundColor = UIColor.orangeColor()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置背景颜色
        self.view.backgroundColor = UIColor.redColor()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "closeClick")
        ///MARK: -加载网页
        let request = NSURLRequest(URL: YXNetworkTool.sharedInstance.oauthURL())
        webview.loadRequest(request)
    }
    
    
    //    填充
    func fillClick(){
        let js = "document.getElementById('userId').value='2825289575@qq.com';" + "document.getElementById('passwd').value='675558256yu';"
        webview.stringByEvaluatingJavaScriptFromString(js)
    }
    //    取消（关闭控制器）
    func closeClick(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //   加载token
    func loadAccessToken(code:String) {
        //      发送网络请求
        YXNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            //          判断是否请求出错
            if error != nil || result == nil {
                SVProgressHUD.showErrorWithStatus("请求出错", maskType: SVProgressHUDMaskType.Black)
                //     延时关闭页面
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.closeClick()
                })
                return
            }
            //没有出错
            //把网络请求返回的数据保存到模型中
            let userAccount = YXUserAccount(dict: result!)
            userAccount.saveAccout()
            AppDelegate.switchViewController(false)
            
            
        }
    }
    
}




/// MARK:- Webview的代理方法（扩展）
extension YXOauthViewController: UIWebViewDelegate{
    ///    开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        //        显示正在加载
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    ///    请求完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    ///    询问是否加载请求 webView加载链接,每当webView加载一个链接都会通过这个代理方法来询问我们这个地址是否可以加载 true表示可以加载, false 就不加载.
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        //        判断加载的不是回调地址
        if !urlString.hasPrefix(YXNetworkTool.sharedInstance.redirect_uri){
            return true//可以加载
        }
        
        //        如果点击的是确定或取消
        if let quety = request.URL?.query{
            //            如果返回地址是code开始的
            let codeString = "code="
            if quety.hasPrefix(codeString){
                //                则按的是确定
                let nsQuery = quety as NSString
                //                截取code的值
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                //                获取access token
                loadAccessToken(code)
            }else{
                //                取消，不授权
                self.closeClick()
            }
        }
        return false
    }
    
}
